import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute  } from '@angular/router'
import { HttpClient } from '@angular/common/http'

@Component({
  selector: 'app-contact-edit',
  templateUrl: './contact-edit.component.html',
  styleUrls: ['./contact-edit.component.css']
})
export class ContactEditComponent implements OnInit {

  formData = {
    name:'',
    email:'',
    phone:'',
    id:0,
  }

  constructor(
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private http:HttpClient
  ) { }

  ngOnInit(): void {
    const contactId = this.activatedRoute.snapshot.params.id
    this.getContactById(contactId)
  }

  getContactById(id):void{
    this.http.get(`http://localhost:3000/contacts/${id}`)
    .toPromise()
    .then((data:any)=>{
      this.formData = data;
    })
    .catch(err=>{
      console.log(err)
    })
  }

  editContact():void{
    const cantactId = this.formData.id;
    this.http.patch(`http://localhost:3000/contacts/${cantactId}`, this.formData)
    .toPromise()
    .then((data:any)=>{
      this.router.navigate(['/'])
    })
    .catch(err=>{
      console.log(err)
    })
  }

}
